package com.coolingme.controller.account;

import com.alibaba.fastjson.JSONObject;
import com.github.xiaoymin.knife4j.annotations.*;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import com.coolingme.domain.entity.SecurityUser;
import com.coolingme.domain.entity.User;
import com.coolingme.domain.vo.PageInfoVo;
import com.coolingme.domain.vo.UserVo;
import com.coolingme.service.UserService;
import com.coolingme.util.ResponseUtil;
import com.coolingme.util.StringUtil;
import com.coolingme.web.response.CommonResp;
import com.coolingme.web.response.CommonRespT;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Slf4j
@Api(tags = "用户接口")
@ApiSupport(order = 2, author = "wangyue")
@ApiResponses({ @ApiResponse(code = 200, message = "success"),
		@ApiResponse(code = 401, message = "Authentication Failure"),
		@ApiResponse(code = 402, message = "Login Information Invalid"),
		@ApiResponse(code = 403, message = "No Permission"), @ApiResponse(code = 420, message = "Data Error"),
		@ApiResponse(code = 421, message = "Cache Error"), @ApiResponse(code = 500, message = "Request fail") })
@RestController
@RequestMapping("/account/user")
public class UserController {

	@Autowired
	private UserService userService;

	@ApiOperation(value = "获取用户基础信息", notes = "获取用户id和userName，必须先登录")
	@ApiOperationSupport(order = 1, responses = @DynamicResponseParameters(properties = {
			@DynamicParameter(value = "状态码", name = "code"), @DynamicParameter(value = "返回信息", name = "msg"),
			@DynamicParameter(value = "返回参数对象", name = "obj", dataTypeClass = User.class) }))
	@GetMapping("/getCurrentUser")
	public User getCurrentUser(@ApiIgnore Authentication authentication) {
		SecurityUser securityUser = (SecurityUser) authentication.getPrincipal();
		User user = new User();
		user.setId(securityUser.getId());
		user.setUserName(securityUser.getUserName());
		return user;
	}

	@ApiOperation(value = "获取用户权限信息", notes = "使用@AuthenticationPrincipal注解，必须先登录")
	@ApiOperationSupport(order = 2, params = @DynamicParameters(), responses = @DynamicResponseParameters(properties = {
			@DynamicParameter(value = "状态码", name = "code"), @DynamicParameter(value = "返回信息", name = "msg"),
			@DynamicParameter(value = "返回参数对象", name = "obj", dataTypeClass = SecurityUser.class) }))
	@GetMapping("/getSecurityUser")
	public SecurityUser getSecurityUser(@ApiIgnore @AuthenticationPrincipal SecurityUser securityUser) {
		Set<String> roles = null;
		Set<String> urls = null;
		try {
			// 通过用户id和用户名查询角色集合
			roles = userService.getRoles(securityUser);
			// 根据role 从redis中获取其所有路径权限集合
			urls = userService.getPermissionURIs(roles);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		securityUser.setRoles(roles);
		securityUser.setPermissionURIs(urls);
		// 设置Security角色
		List<GrantedAuthority> authorities = new ArrayList<>();
		roles.forEach(role -> authorities.add(new SimpleGrantedAuthority(role)));
		securityUser.setAuthorities(authorities);

		log.debug("securityUser" + securityUser);
		return securityUser;
	}

	@ApiOperation(value = "查询用户列表")
	@ApiOperationSupport(order = 3, params = @DynamicParameters(properties = {
			@DynamicParameter(name = "userName", value = "用户名"),
			@DynamicParameter(name = "pageNum", value = "当前页码", required = true, example = "1"),
			@DynamicParameter(name = "pageSize", value = "每页条数", required = true, example = "10") }))
	@PostMapping(value = "/selectPageInfo")
	public CommonRespT<PageInfoVo<UserVo>> selectPageInfo(@RequestBody JSONObject json) {
		int pageNum = json.getIntValue("pageNum");
		int pageSize = json.getIntValue("pageSize");
		String userName = StringUtil.isEmpty(json.getString("userName")) ? null : json.getString("userName");
		PageInfoVo<UserVo> pageInfoVo = userService.selectPageInfo(userName, pageNum, pageSize);
		return ResponseUtil.successT(pageInfoVo);
	}

	@ApiOperation(value = "删除用户", response = CommonResp.class)
	@ApiOperationSupport(order = 4)
	@ApiImplicitParam(name = "id", value = "主键", required = true, dataTypeClass = Integer.class)
	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	public void delete(@RequestBody Integer id) {
		userService.removeById(id);
	}

	@ApiOperation(value = "批量删除用户", response = CommonResp.class)
	@ApiOperationSupport(order = 5)
	@ApiImplicitParam(name = "idList", value = "主键集合", required = true, allowMultiple = true, dataTypeClass = Integer.class)
	@PostMapping(value = "/deleteList")
	public void deleteList(@RequestBody List<Integer> idList) {
		userService.removeByIds(idList);
	}

}
